package com.rh.number.builder;

import com.rh.number.service.impl.NumberFilterService;
import org.apache.ibatis.jdbc.SQL;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class FilterSqlBuilder {
    private static final Logger log = LoggerFactory.getLogger(NumberFilterService.class);
    public String buildFilterSql(Map<String, Object> params) {
        String field = (String) params.get("field");
        Map<String, String> filters = (Map<String, String>) params.get("filters");

        SQL sql = new SQL()
                .SELECT(field + " AS value", "COUNT(*) AS count")
                .FROM("number");

        // 修复条件拼接逻辑
        Optional.ofNullable(filters)
                .orElse(Collections.emptyMap())
                .forEach((col, val) -> {
                    if (StringUtils.hasText(val)) {
                        sql.WHERE(col + " = #{filters." + col + "}");
                    }
                });

        log.debug("完整SQL: {}", sql.toString()); // [!code focus]
        return sql.toString() + " GROUP BY " + field;
    }
}